package com.sweet.serializer;

import com.sweet.enums.SerializerTypeEnum;

import java.io.*;

/**
 * 标准的Java序列化
 *
 * @author limi
 * @version 2020-07-28 16:01
 */
public final class JdkSerializer implements ISerializer {
    @Override
    public SerializerTypeEnum type() {
        return SerializerTypeEnum.JDK;
    }

    @Override
    public byte[] serialize(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }

        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            return baos.toByteArray();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> cls) throws Exception {
        if (bytes == null || bytes.length == 0) {
            return null;
        }

        ObjectInputStream ois = null;
        ByteArrayInputStream bais;
        try {
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            return (T) ois.readObject();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}